package com.own.component.util.database.base.parent;

import org.apache.commons.lang3.StringUtils;

import java.util.Collection;

/**
 * BaseDatabaseSqlProperty
 *
 * @author chenxueli
 * @date 2022-10-15 14:35:00
 */
public interface BaseDatabaseSqlProperty {

    /**
     * 数据库名称的字段
     *
     * @return 数据库名称的字段
     */
    String tableNameField();

    /**
     * 构造sql语句
     *
     * @param sql           原sql
     * @param tableNameList 表名列表
     * @return sql语句
     */
    default String buildTableSql(String sql, Collection<String> tableNameList) {
        if (tableNameList == null || tableNameList.isEmpty()) {
            return sql + " and 0 = 1";
        }
        var tables = tableNameList.stream().filter(StringUtils::isNotBlank).map(name -> "'" + name + "'").toList();
        if (tables.isEmpty()) {
            return sql + " and 0 = 1";
        }
        if (tables.size() == 1) {
            return sql + " and " + tableNameField() + " = " + tables.get(0) + "";
        }
        return sql + " and " + tableNameField() + " in (" + StringUtils.join(tables, ",") + ")";
    }

}
